package com.apes.framework.plugin.soe.metadata;

import com.apes.framework.jpa.BaseModel;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Name;
import com.apes.framework.jpa.generator.ApesGenerator;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;
import org.springframework.util.StringUtils;

import javax.persistence.*;

/**
 * 功能：凭证属性值
 *
 * @author xul
 * @create 2018-09-27 15:51
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = BusinessAttributeValue.CONST_TABLE_NAME, indexes = {
        @Index(name = "u_soe_attr_value", columnList = "business_attr_id, code", unique = true),
        @Index(name = "u_soe_attr_value_code", columnList = "code")})
public class BusinessAttributeValue extends BaseModel {
    public static final String CONST_TABLE_NAME = "soe_business_attr_value";

    @Id
    @Column(name = "id", length = 120)
    //@ApesGenerator(code = CONST_TABLE_NAME, name = "凭证属性值")
    private String id;   //编码

    public void setId(){
        StringBuffer sb = new StringBuffer();
        sb.append(businessAttribute.getId()).append(".").append(code);
        id = sb.toString();
    }

    @ManyToOne(optional = false)
    @JoinColumn(name = "business_attr_id", nullable = false, referencedColumnName = "id")
    private BusinessAttribute businessAttribute; //凭证属性

    @Name
    @Column(name = "code", nullable = false, length = 32)
    private String code;   //属性值

    @Column(name = "name", nullable = false, length = 60)
    private String name; //属性描述

    @Column(name = "valid", columnDefinition = "number(1,0) default 1")
    private boolean valid = true; //是否有效

    public boolean merge(BusinessAttributeValue other) {
        boolean changed = false;
        if (!getCode().equals(other.getCode())) {
            setCode(other.getCode());
            changed = true;
        }
        if (!getName().equals(other.getName())) {
            setName(other.getName());
            changed = true;
        }
        return changed;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof BusinessAttributeValue)) return false;
        BusinessAttributeValue that = (BusinessAttributeValue) o;
        //if (getId() != null ? getId().equals(that.getId()) : false) return true;
        if (!getCode().equals(that.getCode())) return false;
        return getName().equals(that.getName());
    }
}
